/**
 * 
 */
package teehee.UI;

import teehee.DB.DB;
import teehee.Form.SearchPageForm;
//import teehee.UI.AddNewWOD.ButtonClickHandler;
import teehee.homepage.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author Eric, Shub
 *
 */
public class SearchPage extends Activity
{
	protected Button submit;
	protected EditText input; 
	public static DB entry;
	public static boolean fromSearchPage;
	
	String s;
	String result;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        
        //attempt to get text input from user
        submit = ( Button ) findViewById( R.id.SubmitButton );
        input = (EditText)findViewById(R.id.editText1);
        submit.setOnClickListener( new ButtonClickHandler()  );
    }
	/*
	 * turns text input into a string and validates
	 * returns search results for valid input, "" for invalid input
	 */
	public class ButtonClickHandler implements View.OnClickListener {
		public void onClick( View view ) {
			s = input.getText().toString();
			boolean success = SearchPageForm.validate(s);
			if(!success)
			{
				Context context = getApplicationContext();
				CharSequence text = "Exercise/WOD name must only contain letters A-Z and numbers 0-9";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(context, text, duration);
				toast.setGravity(Gravity.TOP|Gravity.LEFT, 25, 300);
				toast.show();
			}
			else
			{
				entry = SearchPageForm.processInput(s);
			if(entry != null)
			{
				fromSearchPage = true;
				Intent history = new Intent(SearchPage.this, ExerciseHistory.class);
        		startActivity(history);
			}
			else
			{
				Context context = getApplicationContext();
				CharSequence text = "Exercise/WOD not found in database";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(context, text, duration);
				toast.setGravity(Gravity.TOP|Gravity.LEFT, 25, 300);
				toast.show();
			}
			}
		}
	}
	@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if ((keyCode == KeyEvent.KEYCODE_MENU)) //replace menu with "SEARCH" to use the search button
        { 
        	//setContentView(R.layout.main);
        	Intent homep = new Intent(SearchPage.this, MainPage.class);
    		startActivity(homep);
            return true;
        }
        return super.onKeyDown(keyCode, event);    
    } 

}
